package com.xiaobo.bodada.aop;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.github.benmanes.caffeine.cache.Cache;
import com.xiaobo.bodada.model.dto.websiteAnalysis.WebsiteAnalysisDTO;
import com.xiaobo.bodada.model.entity.IpInfo;
import com.xiaobo.bodada.utils.NetUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import static com.xiaobo.bodada.constant.CommonConstant.WEBSITE_ANALYSIS_KEY;

/**
 * 请求响应日志 AOP
 *
 * @author xiaobo
 * 
 **/
@Aspect
@Component
@Slf4j
public class LogInterceptor {
    @Resource
    private Cache<String, String> caffeine;

    private static final String IP_FIND_URL = "https://opendata.baidu.com/api.php";

    /**
     * 执行拦截
     */
    @Around("execution(* com.xiaobo.bodada.controller.*.*(..))")
    public Object doInterceptor(ProceedingJoinPoint point) throws Throwable {
        // 计时
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 获取请求路径
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 生成请求唯一 id
        String requestId = UUID.randomUUID().toString();
        String ipAddress = NetUtils.getIpAddress(httpServletRequest);
        String json = caffeine.getIfPresent(WEBSITE_ANALYSIS_KEY + ipAddress);
        if(StrUtil.isBlank(json)){
            CompletableFuture.runAsync(() -> {
                String referer = httpServletRequest.getHeader("Referer");
                HashMap<String, Object> paramMap = new HashMap<>();
                paramMap.put("query", ipAddress);
                paramMap.put("resource_id", "6006");
                paramMap.put("oe", "utf8");
                String ipInfoJson= HttpUtil.get(IP_FIND_URL,paramMap);
                IpInfo ipInfo = JSONUtil.toBean(ipInfoJson, IpInfo.class);
                String location = ipInfo.getData().get(0).get("location");
                WebsiteAnalysisDTO analysisDTO = new WebsiteAnalysisDTO();
                analysisDTO.setVisitIp(ipAddress);
                analysisDTO.setVisitLocation(location);
                analysisDTO.setVisitReferer(referer);
                analysisDTO.setVisitDate(DateUtil.today());
                caffeine.put(WEBSITE_ANALYSIS_KEY+ipAddress, JSONUtil.toJsonStr(analysisDTO));
            });
        }
        System.out.println("缓存："+json);
        String url = httpServletRequest.getRequestURI();
        // 获取请求参数
        Object[] args = point.getArgs();
        String reqParam = "[" + StringUtils.join(args, ", ") + "]";
        // 输出请求日志
        log.info("request start，id: {}, path: {}, ip: {}, params: {}", requestId, url,
                ipAddress, reqParam);
        // 执行原方法
        Object result = point.proceed();
        // 输出响应日志
        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        log.info("request end, id: {}, cost: {}ms", requestId, totalTimeMillis);
        return result;
    }
}

